package com.gamecat.android_tools

import android.app.Application
import android.content.Context
import android.os.Process
import android.text.TextUtils
import com.didichuxing.doraemonkit.BuildConfig
import com.didichuxing.doraemonkit.DoraemonKit
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.bugly.crashreport.CrashReport.UserStrategy
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException


class MyApp :Application() {
    override fun onCreate() {
        super.onCreate()
//        val kits: MutableList<IKit> = ArrayList()
//        kits.add(DemoKit())
//
        DoraemonKit.install(this, "6eaa0542137357bd996a322a30c7bc5f");
//        DoraemonKit.install(this,null,"pId");


        CrashReport.setIsDevelopmentDevice(applicationContext, BuildConfig.DEBUG);

        // 获取当前包名
        // 获取当前包名
        val packageName = packageName
        // 获取当前进程名
        // 获取当前进程名
        val processName: String? = getProcessName1(Process.myPid())
        // 设置是否为上报进程
        // 设置是否为上报进程
        val strategy = UserStrategy(applicationContext)
        strategy.isUploadProcess = processName == null || processName == packageName
//        strategy.appChannel = AppUtil.getAppChannel(context)
        CrashReport.setIsDevelopmentDevice(applicationContext, BuildConfig.DEBUG)
        if (BuildConfig.DEBUG) {
            CrashReport.setUserSceneTag(applicationContext, 66265)
        }
        // 初始化Bugly
        // 初始化Bugly
        CrashReport.initCrashReport(applicationContext, Constants.BUGGLYKEY, BuildConfig.DEBUG, strategy)
        CrashReport.startCrashReport()

    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
//        Multidex.install(this)
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private fun getProcessName1(pid: Int): String? {
        var reader: BufferedReader? = null
        try {
            reader = BufferedReader(FileReader("/proc/$pid/cmdline"))
            var processName: String = reader.readLine()
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim { it <= ' ' }
            }
            return processName
        } catch (throwable: Throwable) {
            throwable.printStackTrace()
        } finally {
            try {
                if (reader != null) {
                    reader.close()
                }
            } catch (exception: IOException) {
                exception.printStackTrace()
            }
        }
        return null
    }
}